use super::config::Config;
use anyhow::{Context, Result};
use log::{info, warn};
use log4rs::config;
use std::env;
use std::fs;
pub fn load_config() -> Result<Config> {
    let path: &'static str = "conf.toml"; // 配置文件路径
    let content = fs::read_to_string(path).with_context(|| format!("无法读取文件: {}", path))?;
    let mut config: Config =
        toml::from_str(&content).with_context(|| "TOML 解析失败，请检查格式或字段类型")?;
    parse_env_args(&mut config);
    Ok(config)
}
use clap::Parser;
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct CliArgs {
    #[arg(short, long, default_value_t = 0)]
    port: u16,
    #[arg(short, long, default_value_t = 0)]
    transfer_port: u16,
    #[arg(short, long, default_value_t = String::from(""))]
    name: String,
}
pub fn parse_env_args(config: &mut Config) {
    // 解析环境变量>命令行参数>配置文件
    let args = CliArgs::parse();
    if args.port > 0 {
        config.address.listen_port = args.port;
    }
    if args.transfer_port > 0 {
        config.address.transfer_port = args.transfer_port;
    }
    config.info.device_name = args.name;
    if let Ok(port) = env::var("PORT") {
        config.address.listen_port = port.parse().unwrap();
    }
    if let Ok(transfer_port) = env::var("TRANSFER_PORT") {
        config.address.transfer_port = transfer_port.parse().unwrap();
    }
    if let Ok(name) = env::var("DEVICE_NAME") {
        config.info.device_name = name;
    }
}
